
import { AppDataSource } from "@/config/database";
import { User } from "@/entities/system/user.entity";
import { ErrorHandler } from "@/middlewares/error.middleware";
import { Context } from "koa";
import * as CryptoJS from 'crypto-js';

export interface IBody {
    /** 用户名（必填） */
    username: string,
    /** 用户昵称（必填） */
    nickname: string,
    /** 用户密码（必填） */
    password: string,
    /** 用户邮箱（必填） */
    email: string,
    /** 用户手机号（可选） */
    phone: string,
    /** 备注信息（可选） */
    remarks?: string,
}

/** 创建用户 */
export async function createUser(ctx: Context) {
    const { username, nickname, password, email, phone, remarks } = ctx.request.body as IBody;

    validateParams(username, password, email); // 校验参数
    await checkUserExists(username, email, phone); // 检查用户名和邮箱是否已存在

    // 创建用户
    const user = await saveUser(username, password, email, nickname, remarks, phone);

    ctx.status = 201;
    ctx.body = {
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        nickname: user.nickname,
        remarks: user.remarks,
        enabledStatus: user.enabledStatus,
    };
}

/** 校验参数 */
const validateParams = (username: string, password: string, email: string) => {
    if (!username || !password || !email) {
        throw new ErrorHandler('用户名、密码和邮箱不能为空', 400);
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        throw new ErrorHandler('邮箱格式不正确', 400);
    }

    // 验证密码强度
    if (password.length < 6) {
        throw new ErrorHandler('密码长度不能少于6位', 400);
    }
}

/** 检查用户名和邮箱是否已存在 */
const checkUserExists = async (username: string, email: string, phone: string) => {
    const userRepository = AppDataSource.getRepository(User);

    // 检查用户名是否存在
    const existingUsername = await userRepository.findOne({
        where: { username }
    });

    if (existingUsername) {
        throw new ErrorHandler('用户名已存在', 409);
    }

    // 检查昵称是否存在
    const existingNickname = await userRepository.findOne({
        where: { nickname: email } // 假设昵称可以与邮箱相同
    });

    if (existingNickname) {
        throw new ErrorHandler('昵称已存在', 409);
    }

    // 检查邮箱是否存在
    const existingEmail = await userRepository.findOne({
        where: { email }
    });

    if (existingEmail) {
        throw new ErrorHandler('邮箱已被注册', 409);
    }

    // 检查手机是否存在
    if (phone) {
        const existingPhone = await userRepository.findOne({
            where: { phone: phone }
        });

        if (existingPhone) {
            throw new ErrorHandler('手机已被注册', 409);
        }
    }
}

/** 保存用户到数据库 */
const saveUser = async (
    username: string,
    password: string,
    email: string,
    nickname?: string,
    remarks?: string,
    phone?: string,
) => {
    const userRepository = AppDataSource.getRepository(User);

    const user = new User();
    user.username = username;
    user.nickname = nickname || username; // 如果没有提供昵称，则使用用户名作为昵称
    user.password = CryptoJS.MD5(password).toString(); // 使用MD5加密密码
    user.email = email;
    user.phone = phone;
    user.remarks = remarks;
    // user.enabledStatus = EnabledStatusEnum.ENABLED;
    // user.createdAt = new Date();
    // user.updatedAt = new Date();

    return await userRepository.save(user);
}


